<?php

namespace Lettral\UserBundle\Controller;

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

use FOS\UserBundle\Entity\UserManager;

use FOS\UserBundle\Controller\RegistrationController as BaseController;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Model\UserInterface;
use Lettral\Helpers\ResponseCreator;
use \Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Lettral\UserBundle\Form\Type\UserFormType;

class RegistrationController extends BaseController
{	
	public function registerAction()
	{
		$request = $this->container->get('request');
	
		$user = $this->container->get('security.context')->getToken()->getUser();
		if (is_object($user) || $user instanceof UserInterface) {
			throw new AccessDeniedException('Vous avez déjà un compte et êtes actuellement connecté.');
		}
	
		$form = $this->container->get('form.factory')->create(new UserFormType());		
	
		if ($request->getMethod() == 'POST') {
	
			$form->bindRequest($request);	
			$um = $this->container->get('fos_user.user_manager');
			$user = $um->createUser($user);
			$user = $form->getData(); // vérifier dans la classe du form que la data_class est bien settée
			$validator = $this->container->get('validator');
			$errors = $validator->validate($user, array('Registration'));
	
			if (count($errors) == 0)
			{	
				$user->setEnabled(true);
				$um->updateUser($user);				
				$em = $this->container->get('doctrine.orm.entity_manager');								
				$em->persist($user);
				$em->flush();
				$this->authenticateUser($user);
				return ResponseCreator::getSuccess();
			}
			else
			{
				return ResponseCreator::getErrorList($errors);
			}
		}
	
		return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.twig',
			array('form' => $form->createView())
		);
	}
	
	protected function authenticateUser(UserInterface $user)
	{
		$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
		$this->container->get('security.context')->setToken($token);
	}
}